package dept_api

import (
	"benkendSystem/database"
	"benkendSystem/models"
	"benkendSystem/utils"
	"github.com/gin-gonic/gin"
	"net/http"
)

// AddDepartment 添加部门请求
func AddDepartment(c *gin.Context) {
	in := new(AddDepartRequest)
	err := c.BindJSON(in)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "系统错误",
		})
		return
	}
	// 初始id
	err = utils.InitSnowflake(1)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "系统错误",
		})
	}
	id := utils.GenerateID()
	// 判断部门是否存在
	var cnt int64
	err = database.DB.Model(new(models.Department)).Where("name = ?", in.Name).Count(&cnt).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "系统错误",
		})
		return
	}
	if cnt > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "部门已存在",
		})
		return
	}
	err = database.DB.Create(&models.Department{
		ID:       id,
		Name:     in.Name,
		ParentID: in.ParentID,
	}).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "操作成功",
	})

}
